// JavaScript Document
$("#register").on('hide.bs.modal',function(){
	//模态框关闭时，执行的动作
});

$(function() {
    getCaptchaImg();

    /*换一张验证码*/
    $('#captchaImg').on('click', function() {
        getCaptchaImg();
    })

    /*登录按钮*/
    $('#loginSubmit').on('click', function() {
        var username = $('#logUsername').val();
        var password = $('#logPassword').val();
        var captchaCode = $('#logCaptchaCode').val();
        var cToken = $.cookie('CTOKEN');
        if((username == '' || username == null) || (password == '' || password == null)){
            alert("用户名和密码均不能为空");
            getCaptchaImg();
            return;
        }
        if(cToken == '' || cToken == null){
            alert("验证码已过期");
            getCaptchaImg();
            return;
        }else if(captchaCode == '' || captchaCode == null){
            alert("请输入验证码");
            getCaptchaImg();
            return;
        }else{
            $.ajax({
                url: '/log',
                method: 'post',
                dataType: 'json',
                type : 'POST',
                data: {
                    'username' : username,
                    'password' : password,
                    'captchaCode' : captchaCode,
                    'CTOKEN' : cToken
                },
                success: function(data) {
                    console.log(data);
                    if(data.resultCode == 1001){
                        window.location.href = '/user/index'
                    }else if(data.resultCode == 1002){
                        alert(data.resultMsg);
                        getCaptchaImg();
                        $('#logUsername').val('');
                        $('#logPassword').val('');
                        $('#logCaptchaCode').val('');
                    }else{
                        alert(data.resultMsg);
                        getCaptchaImg();
                        $('#logCaptchaCode').val('');
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        }

    })
});

/**
 * 获取验证码图片
 */
function getCaptchaImg() {
    $.ajax({
        url: '/captcha/getCaptchaCode',
        method: 'get',
        contentType:'application/json',
        cache: false,
        success: function(data) {
            $('#captchaImg').attr('src', 'data:image/jpeg;base64,' + data);
        },
        error: function(err) {
            console.log(err);
        }
    });
}